<?php

class LogAddForm extends CFormModel
{
    public $order_no;
    public $face_value;
    public $goods_title;
    public $num=1;
    public $prefix_str;





	
	//表单验证规则
	public function rules()
	{
		return array(
            array('order_no,face_value,num,prefix_str', 'required'),
            array('face_value,num', 'numerical','min'=>0.01),
            array('goods_title' , 'safe'),
            array('num', 'numerical','max'=>1000),
        );
	}




	//字段标签
	public function attributeLabels()
	{
        return array(
        "order_no"=>"订单号",
        "face_value"=>"面值",
        "goods_title"=>"备注",
            "num"=>"个数",
            "code"=>"验证码",
            "prefix_str"=>"前缀",
        );
	}

	public function add()
	{
	    $transaction1=ShopCardLog::model()->dbConnection->beginTransaction();
        try {
            $entity = new ShopCardOutLog();
            $entity->num = $this->num;
            $entity->name = $this->goods_title;
            $entity->prefix_str = $this->prefix_str;
            $entity->face_value = $this->face_value*100;
            $entity->admin_id = Yii::app()->session['admin_id'];
            $entity->create_time = date("Y-m-d G:i:s");
            $entity->update_time = date("Y-m-d G:i:s");
            $entity->del_flag = 0;
            $entity->order_no = $this->order_no;
            $entity->save();
            $id= Yii::app()->db1->getLastInsertID();
            $this->order_no = $id;

            $arr = array();
            for ($i = 0; $i < $this->num; $i++) {
                $entity1 = $this->generate();
            }
            $transaction1->commit();

        }catch (Exception $e) {
            $transaction1->rollback();
            return false;
        }
		return true;
	}

    /**
     * @param $entity
     * @param int $type
     * @return ShopCardLog
     */
    public function generateCode($entity,$type=1) {
        $entity1 = new ShopCardLog();
        $entity1->status = 0;
        $entity1->goods_title = $entity->goods_title;

        $prefix_str = strtoupper($this->prefix_str);
        $len = 5-strlen($prefix_str);
        if ($len>0) {
            $prefix_str = $prefix_str.$this->createCode($len);
        }
        $code = $prefix_str."-".$this->createCode()."-".$this->createCode()."-".$this->createCode();

        $aes = new Aes();

        $entity1->code_str =$aes->encrypt($code);
        $entity1->log_id = $entity->order_no;
        $entity1->face_value = $entity->price;
        $entity1->create_time = date("Y-m-d G:i:s");
        $entity1->update_time = date("Y-m-d G:i:s");
        $entity1->del_flag=0;
        $return = $entity1->save();
        if ($return) {
            return $entity1;
        }
        return false;
    }

    /**
     * @return card_log|false
     */
    public function generate() {
	    $e = new GCardModel();
	    $e ->goods_title = $this->goods_title;
        $e->user_id = Yii::app()->session['admin_id'];
        $e->order_no = $this->order_no;
        $e->price = $this->face_value*100;
        Yii::app()->session['codestr'] = "";
        return $this->generateCode($e,2);
    }

    /**
     * @param $phone
     * @param $msg
     * @return mixed
     */
    function mobileForHk($phone, $msg)
    {
        $data=array(
            "account"=>"dh31961",
            "password"=>"e6df30ad7cd07f96327003ed0b4c502a",
            "phones"=>$phone,
            "sign"=>"【凤凰游戏商城】",
            "content"=>$msg,
        );
        $result=json_decode(sendPost("http://www.dh3t.com/json/sms/Submit",json_encode($data)),true);
        return $result;
    }

    /**
     * @param int $num
     * @return string
     */
    function createCode($num=5) {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)]
            .strtoupper(dechex(date('m')))
            .date('d')
            .substr(time(),-5)
            .substr(microtime(),2,5)
            .sprintf('%02d',rand(0,99));
        for(
            $a = md5( $rand, true ),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
            $d = '',
            $f = 0;
            $f < $num;
            $g = ord( $a[ $f ] ),
            $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
            $f++
        );

        return $d;
    }

    /**
     * @return mixed
     */
    function send(){
        $phone = "13588833305";
        $code = $this->createCode();
        Yii::app()->session['codestr'] = $code;
        return $this->mobileForHk($phone,"您正在导出游戏点卡，验证码".$code."请不要透漏给别人");
    }

    /**
     * @param $orderNo
     * @return array
     */
    public function findByOrderNo($orderNo) {
        $list1  = card_log::model()->findAll('order_no=:order_no and del_flag=:del_flag', array(':order_no'=>$orderNo,':del_flag'=>0));
        $list = [];
        $aes = new Aes();
        foreach ($list1 as $e) {
            $list[] = [
                "faceValue"=>$e->face_value,
                "codeStr"=>$aes->decrypt($e->code_str)
            ];
        }
        return $list;
    }

    /**
     * @param $codeStr
     * @return mixed
     * @throws Exception
     */
    public function findByCodeStr($codeStr) {
        $entity=card_log::model()->find('code_str=:code_str and del_flag=:del_flag', array(':code_str'=>$codeStr,':del_flag'=>0));
        if(!$entity) {
            throw new Exception("卡密错误","2003");
        }
        return $entity;
    }

    public function useCode($code,$ip,$appId) {
        $entity = $this->findByCodeStr($code);

        if ($entity->status != 0) throw new Exception("卡密不存在",2002);
        $num = card_log::model()->updateAll([
            'status' => 1,
            'sell_status'=>"1",
            "use_time"=>date("Y-m-d G:i:s"),
            'use_ip' => $ip,
            'use_platform' => $appId,
            "update_time"=>date("Y-m-d G:i:s"),
        ],"status=:status and del_flag=:del_flag and code_str=:code_str", ["status"=>0,"del_flag"=>0,"code_str"=>$code]);
        if ($num == 0) throw new Exception("卡密使用失败","2001");
        return $entity->face_value;
    }

    public function check($code)
    {
        $entity = $this->findByCodeStr($code);
        if ($entity->status != 0) throw new Exception("卡密不存在",2002);
        return $entity->face_value;
    }

}